import React from 'react';
import { Tree } from 'antd';
import { menu } from '@/services/Role';

class Access extends React.Component {
  constructor(props) {
    super(props);
    this.checkedKeys = [];
    this.state = { treeData: [] }
  }

  /* 获取权限菜单 */
  getMenus = async () => {
    const { checkedKeys } = this;
    const { id, check } = this.props;
    const res = !id ? await menu() : await menu(id);
    const threes = this._getThrees(res);
    this.setState({
      treeData: threes
    })
    check ? check(checkedKeys) : null;
  }

  /* 获取树数据 */
  _getThrees = (list) => {
    const arr = [];
    if (!list || list.length === 0) return [];
    for (let i = 0; i < list.length; i++) {
      const item = list[i];
      item.isHas === 1 ? this.checkedKeys.push(item.id) : null;
      arr.push({
        key: item.id,
        title: item.name,
        children: this._getThrees(item.childMenu)
      })
    }
    return arr
  }

  /* 监听选中 */
  onCheck = (checkedKeys, e) => {
    const { check } = this.props
    const checked = [...e.halfCheckedKeys, ...checkedKeys];
    check ? check(checked) : null;
  }

  /* 获取权限视图 */
  // getMenusView = (list) => {
  //   const arr = [];
  //   for (let i = 0; i < list.length; i ++) {
  //     const item = list[i];
  //     arr.push(
  //       <div key={item.code} className={styles.itemContainer}>
  //         <div>{item.name}</div>
  //         <div>{item.child ? this.getMenusView(item.child) : null}</div>
  //       </div>
  //     )
  //   }
  //   return arr
  // }

  componentDidMount() {
    this.getMenus();
  }

  render() {
    const { onCheck, checkedKeys } = this;
    const { treeData } = this.state;
    const { disabled } = this.props;
    if (treeData.length === 0) return null;
    return (
      <Tree
        checkable
        disabled={disabled}
        draggable
        expandedKeys={checkedKeys}
        defaultCheckedKeys={checkedKeys}
        treeData={treeData}
        onCheck={onCheck} />
    )
  }
}

export default Access